import _isEmpty from "lodash/isEmpty";
// import CrypotoJS from "crypto-js";

export default class LocalStorageUtil {
  static instance: LocalStorageUtil | null = null;

  static getInstance() {
    if (this.instance == null) {
      this.instance = new LocalStorageUtil();
    }
    return this.instance;
  }

  setItem(key: string, value: any): boolean {
    try {
      let _value = "";
      if (typeof value !== "string") {
        // 不是字符串统一JSON转成字符串
        _value = JSON.stringify(value);
      }
      window.localStorage.setItem(key, _value);
      return true;
    } catch (e) {
      return false;
    }
  }

  getItem<T>(key: string): T | null {
    let result = window.localStorage.getItem(key);
    if (!result) {
      return null;
    } else {
      const _result = <T>JSON.parse(result);
      return _isEmpty(_result) ? null : _result;
    }
  }

  clearItem(key: string): void {
    window.localStorage.removeItem(key);
  }

}
